package com.banciyuan.bcywebview.biz.main.message.messagedetail;

import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.MessageApi;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.helper.ActionbarHelper;
import com.banciyuan.bcywebview.base.helper.FlagUtils;
import com.banciyuan.bcywebview.base.helper.LoadingHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshListView;
import com.banciyuan.bcywebview.utils.http.CommonApiUtils;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.daoexample.model.Message;

import static com.banciyuan.bcywebview.base.factory.MessageFactory.MESSAGE_TYPE_OTHER;
import static com.banciyuan.bcywebview.base.factory.MessageFactory.inWhichType;


/**
 * Created by hy on 2015/12/18.
 */
public class MessageDetailActivity extends BaseActivity {
    public static final int MESSAGE_REMIND = 12;
    public static final int MESSAGE_NOTIFY = 13;
    public static final int MESSAGE_NOVEL = 14;

    private boolean loading = false;
    private int page = 1;

    private List<Message> mlist = new ArrayList<>();
    private LoadingHelper mProgressbarHelper;
    private View mProgressbarView;
    private PullToRefreshListView mRefreshLv;
    private ListView mContentLv;
    private MessageListviewAdapter mAdapter;
    private int messageType = MESSAGE_REMIND;
    private TextView tvDescOne;
    private TextView tvDescTwo;
    private View parentView;
    private ActionbarHelper mActionbarHelper;
    private View mActionBarView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        parentView = View.inflate(this, R.layout.activity_messagedetail, null);
        setContentView(parentView);
        initArgs();
        initProgressbar();
        initActionbar();
        initUi();
        initAction();
        initData();
    }

    @Override
    protected void initArgs() {
        messageType = getIntent().getIntExtra(gotoUtil.INTENT_VALUE_ONE, MESSAGE_NOTIFY);
    }

    @Override
    protected void initProgressbar() {
        mProgressbarView = findViewById(R.id.base_progressbar);
        mProgressbarHelper = new LoadingHelper(parentView);
        tvDescOne = (TextView) findViewById(R.id.tv_desc_one);
        tvDescTwo = (TextView) findViewById(R.id.tv_desc_two);
        findViewById(R.id.iv_empty_pic_two).setVisibility(View.GONE);
        switch (messageType) {
            case MESSAGE_REMIND:
            default:
                tvDescOne.setText(getString(R.string.notify_notyet));
                tvDescTwo.setText(getString(R.string.friend_join_in));
                break;
            case MESSAGE_NOTIFY:
                tvDescOne.setText(getString(R.string.message_notyet));
                tvDescTwo.setText(getString(R.string.quick_replay_friend));
                break;
            case MESSAGE_NOVEL:
                tvDescOne.setText(getString(R.string.series_emptydesc));
                tvDescTwo.setVisibility(View.INVISIBLE);
                break;
        }
        mProgressbarHelper.setActionCallbacks(new LoadingHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                mProgressbarHelper.onLoading();
                initData();
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initActionbar() {
        mActionBarView = findViewById(R.id.base_action_bar);
        mActionbarHelper = new ActionbarHelper(this, mActionBarView);
        switch (messageType) {
            case MESSAGE_NOTIFY:
                mActionbarHelper.setTitle(getResources().getString(R.string.comment));
                break;
            case MESSAGE_REMIND:
                mActionbarHelper.setTitle(getResources().getString(R.string.remind));
                break;
            case MESSAGE_NOVEL:
                mActionbarHelper.setTitle(getResources().getString(R.string.order_serialize));
                break;
        }
    }

    @Override
    protected void initUi() {
        mRefreshLv = (PullToRefreshListView) findViewById(R.id.message_message_list);
        mContentLv = mRefreshLv.getRefreshableView();
    }

    @Override
    protected void initAction() {
        mRefreshLv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                getFrontDataTask();
            }
        });

        mRefreshLv.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                if (!loading) {
                    page++;
                    loading = true;
                    getFrontDataTask();
                }
            }
        });
        mContentLv.setAdapter(mAdapter);
    }

    @Override
    protected void initData() {
        page = 1;
        loading = false;
        getFrontDataTask();
    }


    private void getFrontDataTask() {
        switch (messageType) {
            case MESSAGE_REMIND:
                getMessageData(MessageApi.getRemind());
                break;
            case MESSAGE_NOTIFY:
                getMessageData(MessageApi.getNotify());
                break;
            case MESSAGE_NOVEL:
                getMessageData(MessageApi.getNovelupdate());
                break;

        }
    }

    public void getMessageData(String action) {
        loading = true;
        Response.Listener<String> onSuccess = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    if (StatusCodeUtils.dealStatusCode(response, MessageDetailActivity.this)) {
                        JSONObject jsonObject = new JSONObject(response);
                        String result = jsonObject.getString(HttpUtils.UPLOAD_DATA);
                        Gson gson = new Gson();
                        List<Message> templist = gson.fromJson(result, new TypeToken<List<Message>>() {
                        }.getType());
                        popIllegalData(templist);
                        if (page == 1 && templist.isEmpty()) {
                            onNodataError();
                        } else {
                            renderData(templist);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                onNetworkError();
            }
        };

        CommonApiUtils.getMessageTipsData(this, VolleyQueue.getRquest(this), onSuccess, onError, page, UserDataHelper.getInstance(this).getToken(), action);
    }

    private void renderData(List<Message> templist) {
        if (page == 1) {
            mlist.clear();
        }
        mlist.addAll(templist);
        if (mAdapter == null) {
            mAdapter = new MessageListviewAdapter(this, mlist);
            mRefreshLv.setAdapter(mAdapter);
        } else {
            mAdapter.notifyDataSetChanged();
        }
        frontDataSuccess();
    }


    public void onNetworkError() {
        mRefreshLv.onRefreshComplete();
        mProgressbarHelper.onFailed();
        loading = false;
    }

    public void frontDataSuccess() {
        mAdapter.updateData();
        mRefreshLv.onRefreshComplete();
        mProgressbarHelper.onSuccess();
        loading = false;
        if (page == 1) {
            switch (messageType) {
                case MESSAGE_REMIND:
                    if (FlagUtils.ifRemindUpdate) {
                        FlagUtils.ifRemindUpdate = false;
                    }
                    break;
                case MESSAGE_NOTIFY:
                    if (FlagUtils.ifNotifyUpdate) {
                        FlagUtils.ifNotifyUpdate = false;
                    }
                    break;
                case MESSAGE_NOVEL:
                    if (FlagUtils.ifSerializeUpdate) {
                        FlagUtils.ifSerializeUpdate = false;
                    }
                    break;
            }
        }
    }

    public void onNodataError() {
        loading = false;
        mRefreshLv.onRefreshComplete();
        switch (messageType) {
            case MESSAGE_REMIND:
            default:
                mProgressbarHelper.onNodata();
                break;

            case MESSAGE_NOTIFY:
                mProgressbarHelper.onNodata();
                break;
        }
    }

    private static List<Message> popIllegalData(List<Message> tempData) {
        List<Message> mData = new ArrayList<>();
        for (int i = 0; i < tempData.size(); i++) {
            int whichType = inWhichType(tempData.get(i).getType());
            if (whichType != MESSAGE_TYPE_OTHER) {
                mData.add(tempData.get(i));
            }
        }
        return mData;
    }
}
